package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("===================开始缓存初始化====================");
        //初始化第一步,从MongoDB中拿取所有攻略对象
        List<Strategy> list = strategyService.selectAll();
        //初始化第二步,将所有攻略对象转为StrategyStaticVO对象,存入Redis缓存库中
        //但对于缓存中已有的攻略对象对应的VO对象,不进行生成
        for (Strategy strategy : list) {
            if (strategyStatisVORedisService.isStrategyVOExists(strategy.getId())){
                //存在,进入下次循环
                continue;
            }
            //不存在,创建Vo对象,进行缓存到Redis操作
            StrategyStatisVO vo=new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }
        System.out.println("===================缓存初始化结束====================");
    }
}
